import { getMenuListAndButtonList } from '@/api/menuAndButton.js'
import router, { constantRoutes, resetRouter, anyRoute } from '@/router'
import { setTokenTime } from '@/utils/auth.js'
import { getAllMenuList as acquireAllMenuList } from '@/api/authority.js'
import { handleTokenExpire } from '@/utils/handleTokenExpire.js'

export default {
  namespaced: true,
  state: () => ({
    token: localStorage.getItem('token') || '',
    siderType: true,
    lang: localStorage.getItem('lang') || 'zh',
    buttonList: [],
    allMenuList: [],
    returnUserMenuList: [],
    treeAllMenuList: [],
    menuNameAndIdList: [],
    mapInfoList: [],
    themeStatus: false
  }),
  mutations: {
    setThemeStatus(state, isDark) {
      state.themeStatus = isDark
    },
    setToken(state, token) {
      state.token = token
      localStorage.setItem('token', token)
    },
    changeSiderType(state) {
      state.siderType = !state.siderType
    },
    changeLang(state, lang) {
      state.lang = lang
    },
    saveMenuListAndButtonList(
      state,
      { buttonList, newMenuList, returnUserMenuList }
    ) {
      state.buttonList = buttonList
      state.allMenuList = newMenuList
      state.returnUserMenuList = returnUserMenuList
    },
    clearMenuAndButtonList(state) {
      state.buttonList = []
      state.allMenuList = []
      state.returnUserMenuList = []
    },
    resetState(state) {
      state.token = ''
      state.siderType = true
      state.buttonList = []
      state.allMenuList = []
      state.returnUserMenuList = []
    },
    saveTreeAllMenuList(state, treeAllMenuLists) {
      state.treeAllMenuList = treeAllMenuLists[0].children
    },
    saveMapInfoList(state, handlerRes) {
      state.mapInfoList = handlerRes
    }
  },
  actions: {
    // 存储token 和 生成token时间
    login({ commit }, token) {
      commit('setToken', token)
      setTokenTime()
    },
    //#region
    /*    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginApi(userInfo)
          .then((res) => {
            commit('setToken', res.token)
            // 设置tokenTime
            setTokenTime()
            // 成功后跳转首页
            router.replace('/')
            resolve()
          })
          .catch((err) => {
            // location.reload()
            reject(err)
          })
      })
    }, */
    //#endregion
    logout({ commit }) {
      commit('clearMenuAndButtonList')
      // 重置路由
      // resetRouter()
      // 重置state中的token
      commit('setToken', '')
      // 清空localStorage lang tokenTime token
      // localStorage.clear() // 全部清除这里最好不要这么做会造成记住密码失败 除非使用cookie方式存储密码
      localStorage.removeItem('lang')
      localStorage.removeItem('token')
      localStorage.removeItem('tokenTime')
      localStorage.removeItem('loglevel:webpack-dev-server')
      // 解决退出时路由缓存问题，这个有待优化，按理来说使用router.removeRoute就好
      // 实际会出现组件找不到的bug,目前动态添加其他路由在数据库是没有问题的
      location.reload()
      // 路由跳转到首页
      // router.replace({ path: '/login' })
    },
    // 获取当前登陆的用户菜单
    async getMenuListAndButtonLists({ commit }) {
      const res = await getMenuListAndButtonList()
      // console.log(res)
      if (res.code === 200) {
        const { buttonList, userMenuList } = res.data
        // 获取返回的菜单 调用方法处理菜单
        const returnUserMenuList = handlerMenuList(userMenuList)
        // 获取全部菜单列表(按钮列表用来匹配按钮的权限，菜单列表这里仅用来遍历左侧侧边栏)
        const menuList = getAllMenuList(returnUserMenuList, constantRoutes)
        const newMenuList = handlerRoutes(menuList)
        const data = { buttonList, newMenuList, returnUserMenuList }
        commit('saveMenuListAndButtonList', data)
        // console.log(router.getRoutes())
      } else {
        Promise.reject(res.message)
      }
    },
    // 获取全部菜单
    async getTreeAllMenuList({ commit, state }) {
      try {
        const menuList = await acquireAllMenuList()
        // console.log(menuList.data)
        commit('saveTreeAllMenuList', menuList.data)
        state.menuNameAndIdList = handlerTreeMenuList(menuList.data)
      } catch (error) {
        handleTokenExpire(error)
      }
    }
  }
}

// 处理菜单获得type=1的全部菜单并将存储为[{ id: '1', name: '顶级' },{xxx}]
function handlerTreeMenuList(arr, init = []) {
  return arr.reduce((prev, current) => {
    const { id, name } = current
    if (current.type === '1' || current.type === '0') {
      prev.push({ id, name })
    }
    if (current.children && current.children.length) {
      handlerTreeMenuList(current.children, init)
    }
    return prev
  }, init)
}

// 对路由处理去除hidden=true
function handlerRoutes(constantRoutes) {
  return constantRoutes.filter((item) => {
    if (item.hidden) {
      return false
    }
    if (item.children && item.children.length) {
      item.children = handlerRoutes(item.children)
    }
    return true
  })
}

// 获取当前全部的路由(除了任意路由)
function getAllMenuList(userList, constantList) {
  const res = []
  constantList.forEach((item) => {
    if (item.children && item.children.length) {
      userList.forEach((child) => {
        item.children.push(child)
      })
    }
    res.push(item)
  })
  return res
}

const finalArr = []
function handlerMenuList(arr) {
  arr.forEach((item) => {
    const { path, name, component } = item
    let newObj = {}
    newObj = { path, name, component }
    if (item.children && item.children.length) {
      // 处理子项
      newObj.children = getSelectChildrenArr(item.children)
    }
    finalArr.push(newObj)
  })
  return finalArr
}

function getSelectChildrenArr(children) {
  const temArr = []
  children.forEach((child) => {
    if (child.children && child.children.length) {
      handlerMenuList(child.children)
    } else {
      let temObj = {}
      const { path, name, component } = child
      temObj = { path, name, component }
      temArr.push(temObj)
    }
  })
  return temArr
}
